﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsOpen
{
    public partial class Form1 : Form
    {
        private List<Form2> form2 = new List<Form2>();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (form2.Count < 3)
            {
                Form2 newSubForm = new Form2();
                newSubForm.FormClosedEvent += NewSubForm_FormClosed;
                newSubForm.Text = "SubForm " + (form2.Count + 1);
                newSubForm.Show();
                form2.Add(newSubForm);
            }
            else
            {
                form2[form2.Count - 1].Activate();
            }
        }

        private void NewSubForm_FormClosed(object sender, EventArgs e)
        {
            Form2 closedSubForm = sender as Form2;
            if (closedSubForm != null && form2.Contains(closedSubForm))
            {
                form2.Remove(closedSubForm);
                closedSubForm.FormClosedEvent -= NewSubForm_FormClosed; // 移除事件处理程序
            }
        }
    }
}
